package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollPageDTO;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.lang.model.type.IntersectionType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Autowired
    IUserService userService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    IFollowService followService;

    @Override
    public Result queryById(Long id) {
        Blog blog = query().eq("id", id).one();
        queryBlogUser(blog);
        isLikedBlog(blog);
        return Result.ok(blog);
    }

//    是否是点赞博客
//    查询的时候加上
    private void isLikedBlog(Blog blog) {
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        if(UserHolder.getUser()==null) return;
        String userId = UserHolder.getUser().getId().toString();
//        blog的userId
//        String userId = blog.getUserId().toString();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId);
        if (score!=null)
            blog.setIsLike(true);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
                    queryBlogUser(blog);
                    isLikedBlog(blog);
                }
        );
        return Result.ok(records);
    }

    @Override
    public Result likeBlog(Long id) {
//        return likeBlogSet(id);
        return likeBlogZset(id);
    }

    @Override
    public Result likeUsers(Long id) {
        //查询前五的用户id
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Set<String> zset = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (CollectionUtil.isEmpty(zset)) return Result.ok(zset);
//        //将里面的字符串转为Long类型的
//        //里面没有score
        List<Long> ids = zset.stream().map(Long::valueOf).collect(Collectors.toList());
//        //字符串拼接，按照正确的顺序
        String join = StrUtil.join(",", ids);

        //通过用户id查询数据库
//        //直接使用in
//        //SELECT id FROM `tb_user` where id in (2,1) order by FIELD(id,2,1)
//        //这样才能按照正确的顺序
        List<User> users = userService.query().in("id", ids).last("order by FIELD(id,"+join+")").list();
        List<UserDTO> userDTOS = users.stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        //转为DTO返回给前端
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean save = save(blog);
        if (!save) return Result.fail("发布博文失败");
        //发送给关注者
        List<Follow> follows = followService.query().eq("follow_user_id", blog.getUserId()).list();
        follows.forEach(follow -> {
            stringRedisTemplate.opsForZSet().add(FEED_KEY+follow.getUserId(),blog.getId().toString(),System.currentTimeMillis());
        });
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result ofFollow(Long maxTime, Long offSet) {
        //查询数据
        String userId = UserHolder.getUser().getId().toString();
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(FEED_KEY + userId, 0, maxTime, offSet, 2);
        if (CollectionUtil.isEmpty(typedTuples)) return Result.ok();
        List<String> ids = new ArrayList<>();
        Long miniTime = 0L;
        Long os=1L;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            ids.add(typedTuple.getValue());
            Long time = typedTuple.getScore().longValue();
            if(miniTime.equals(time)){
                os++;
            }else{
                os=1L;
                miniTime=time;
            }
        }
        String strIds = StrUtil.join(",", ids);
        //查询博客 order by field(id,ids)
        List<Blog> blogs = query().in("id", ids).last("order by field(id," + strIds + ")").list();
        //处理博客
        blogs.forEach(blog -> {
            queryBlogUser(blog);
            isLikedBlog(blog);
        });
        //返回博客，miniTime和偏移量
        ScrollPageDTO scrollPageDTO = new ScrollPageDTO(blogs,miniTime,os);
        return Result.ok(scrollPageDTO);
    }

    private Result likeBlogZset(Long id) {
        //判断用户是否点赞
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        String userId = UserHolder.getUser().getId().toString();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId);

        //未点赞
        //加入redis，修改数据库
//        使用工具类，防止拆箱空指针
        if (score==null) {
//            更新操作完了后再操作redis
//            .update
//            更新成功了再操作
            boolean update = update().eq("id", id).setSql(" liked = liked + 1 ").update();
            if (update) stringRedisTemplate.opsForZSet().add(key,userId,System.currentTimeMillis());
        } else {
            //已点赞
            //移除redis，修改数据库
            boolean update = update().eq("id", id).setSql("liked = liked - 1").update();
            if (update) stringRedisTemplate.opsForZSet().remove(key,userId);
        }

        return Result.ok();
    }


    private Result likeBlogSet(Long id) {
        //判断用户是否点赞
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        String userId = UserHolder.getUser().getId().toString();
        Boolean member = stringRedisTemplate.opsForSet().isMember(key, userId);

        //未点赞
        //加入redis，修改数据库
//        使用工具类，防止拆箱空指针
        if (BooleanUtil.isFalse(member)) {
//            更新操作完了后再操作redis
//            .update
//            更新成功了再操作
            boolean update = update().eq("id", id).setSql(" liked = 1 ").update();
            if (update) stringRedisTemplate.opsForSet().add(key, userId);
        } else {
            //已点赞
            //移除redis，修改数据库
            boolean update = update().eq("id", id).setSql("liked = 0").update();
            if (update) stringRedisTemplate.opsForSet().remove(key, userId);
        }

        return Result.ok();
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
